package com.eascs.ticket.ticket.service;

import java.util.Date;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.ticket.common.entity.EntityUtil;
import com.eascs.ticket.common.service.BaseSevice;
import com.eascs.ticket.ticket.entity.TicketStatusTimeLog;

@Service
public class TicketStatusTimeLogService extends BaseSevice {
	@Inject
	private TicketTimeLogService ticketTimeLogService;

	@Transactional(transactionManager = "ticketTransactionManager")
	public TicketStatusTimeLog insertStartTimeLog(String ticketId, String status, String operator, Date startTime) {
		TicketStatusTimeLog ticketStatusTimeLog = this.getTicketStatusTimeLog(ticketId, status, operator);
		if (null != ticketStatusTimeLog) {
			return ticketStatusTimeLog;
		}
		ticketStatusTimeLog = new TicketStatusTimeLog();
		ticketStatusTimeLog.setTicketId(ticketId);
		ticketStatusTimeLog.setStatus(status);
		ticketStatusTimeLog.setOperator(operator);
		ticketStatusTimeLog.setStartTime(startTime);
		EntityUtil.initInsertEntity(ticketStatusTimeLog);
		this.insertTicketStatusTimeLog(ticketStatusTimeLog);
		ticketTimeLogService.insertTicketTimeLog(ticketId, operator, startTime);
		return ticketStatusTimeLog;
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public void updateEndTimeLog(String ticketId, String status, String operator, Date endTime) {
		TicketStatusTimeLog ticketStatusTimeLog = this.getTicketStatusTimeLog(ticketId, status, operator);
		if (null == ticketStatusTimeLog) {
			ticketStatusTimeLog = this.insertStartTimeLog(ticketId, status, operator, endTime);
		}
		ticketStatusTimeLog.setEndTime(endTime);
		EntityUtil.initUpdateEntity(ticketStatusTimeLog);
		this.proxyDao.updateById(ticketStatusTimeLog);
		ticketTimeLogService.updateTicketTimeLog(ticketId, operator, endTime);
	}

	public TicketStatusTimeLog getTicketStatusTimeLog(String ticketId, String status, String operator) {
		TicketStatusTimeLog ticketStatusTimeLog = new TicketStatusTimeLog();
		ticketStatusTimeLog.setTicketId(ticketId);
		ticketStatusTimeLog.setStatus(status);
		ticketStatusTimeLog.setOperator(operator);
		return this.proxyDao.findEntityWithAny(ticketStatusTimeLog);
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public void insertTicketStatusTimeLog(TicketStatusTimeLog ticketStatusTimeLog) {
		this.proxyDao.insert(ticketStatusTimeLog);
	}

}
